<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" ref="queryForm">
      <el-form-item label="菜单名称">
        <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入菜单名称" v-model="queryParams.name" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" icon="el-icon-search" type="primary">搜索</el-button>
        <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button @click="handleAdd" class="mb-10" icon="el-icon-plus" plain type="primary">新增</el-button>

    <!-- 数据表格 -->
    <el-table
      :data="pageList"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      border
      highlight-current-row
      row-key="id"
      v-loading="loading"
    >
      <el-table-column label="菜单名称" prop="name"></el-table-column>
      <el-table-column label="菜单图标">
        <template slot-scope="{row}">
          <p class="fz-18" v-if="row.icon">
            <svg-icon :iconClass="row.icon" />
          </p>
          <p v-else>-</p>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.visible==1">显示</el-tag>
          <el-tag type="info" v-else>隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <el-button @click.stop="handleUpdate(row)" circle icon="el-icon-edit" plain type="primary" />
          <el-button @click.stop="handleAdd(row)" circle icon="el-icon-plus" plain type="success" />
          <!-- <el-button @click.stop="handlePermission(row)" circle icon="el-icon-key" plain type="info" /> -->
          <el-button @click.stop="handleDelete(row)" circle icon="el-icon-delete" plain type="danger" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹框 -->
    <el-dialog :before-close="handleClose" :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" label-width="25%" ref="form">
        <el-form-item label="上级菜单">
          <el-cascader
            :options="menuOptions"
            :props="{ checkStrictly: true, emitPath: false, label: 'name', value: 'id' }"
            :show-all-levels="false"
            clearable
            v-model="form.parentId"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="菜单名称" prop="name">
          <el-input placeholder="请输入菜单名称" v-model="form.name" />
        </el-form-item>

        <el-form-item label="菜单图标">
          <el-popover @show="$refs['iconSelect'].reset()" placement="bottom-start" trigger="click" width="460">
            <IconSelect @selected="handleIconSelected" ref="iconSelect" />
            <el-input placeholder="点击选择图标" readonly slot="reference" v-model="form.icon">
              <svg-icon :icon-class="form.icon" class="el-input__icon" slot="prefix" style="width: 16px; " v-if="form.icon" />
              <i class="el-icon-search el-input__icon" slot="prefix" v-else />
            </el-input>
          </el-popover>
        </el-form-item>

        <el-form-item label="路由路径" prop="routePath">
          <el-input placeholder="父路由例如：/admin；子路由省略斜杠/，例如：user" v-model="form.routePath" />
        </el-form-item>

        <el-form-item label="组件路径">
          <el-input placeholder="/admin/user/index" v-model="form.componentPath">
            <template slot="prepend" v-if="form.parentId!='0'">src/views</template>
            <template slot="append" v-if="form.parentId!='0'">.vue</template>
          </el-input>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.visible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :min="0" controls-position="right" style="width: 100px" v-model="form.sort" />
        </el-form-item>

        <el-form-item label="重定向路径">
          <el-input maxlength="50" placeholder="请输入重定向路径" v-model="form.redirectPath" />
        </el-form-item>

        <el-form-item>
          <el-button @click="handleSubmit" type="primary">保存</el-button>
          <el-button @click="resetForm" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import IconSelect from '@components/common/IconSelect'
import Api from '../api'

export default {
  name: 'Menu',
  components: { IconSelect },
  data() {
    return {
      loading: true,
      ids: [],
      // 查询表单数据
      queryParams: {
        name: undefined,
        queryMode: undefined
      },
      // 页码数据
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 数据列表
      pageList: [],
      // 新增表单数据
      form: {
        parentId: '0',
        visible: 1,
        icon: undefined,
        sort: 1,
        componentPath: ''
      },
      // 校验规则
      rules: {
        parentId: [
          { required: true, message: '请选择顶级菜单', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        routePath: [
          { required: true, message: '请输入路由路径', trigger: 'blur' }
        ],
        componentPath: [
          { required: true, message: '请输入组件', trigger: 'blur' }
        ]
      },
      // 弹框标题
      title: '新增菜单',
      menuOptions: [],
      currentRow: undefined,
      // 弹框显示标识
      dialogVisible: false

    }
  },
  created() {
    this.loadMenuOptions()
    this.handleQuery()
  },
  methods: {
    // 数据请求
    handleQuery() {
      this.resetForm()
      this.queryParams.current = this.pagination.current
      this.queryParams.size = this.pagination.size
      this.queryParams.queryMode = '1'
      Api.getMenuList(this.queryParams).then(data => {
        this.pageList = data.records
        this.pagination.total = data.total
      }).finally(() => { this.loading = false })
    },
    // 表单重置
    handleReset() {
      this.pagination = {
        current: 1,
        size: 10,
        total: 0
      }
      this.queryParams.name = undefined
      this.handleQuery()
    },
    // 行点击
    handlePermission(row) {
      this.$emit('menuClick', row)
    },
    // 新增
    handleAdd(row) {
      this.dialogVisible = true

      this.resetForm()
      if (row.id) { // 行点击新增
        this.form.parentId = row.id
      } else { // 工具栏点击新增
        if (this.currentRow) {
          this.form.parentId = this.currentRow.id
        } else {
          this.form.parentId = '0'
          this.form.componentPath = ''
        }
      }
      this.title = '新增菜单'
    },
    // 更改
    handleUpdate(row) {
      this.dialogVisible = true

      this.resetForm()
      this.title = '修改菜单'
      this.form = JSON.parse(JSON.stringify(row))
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false
    },
    // 提交
    handleSubmit() {
      this.dialogVisible = true

      this.$refs.form.validate(valid => {
        if (valid) {
          Api.addOrUpdateMenu(this.form).then(() => {
            this.$message.success(this.form.id ? '修改成功' : '新增成功')
            this.handleQuery()
          }).finally(() => { this.dialogVisible = false })
        }
      })
    },
    // 删除
    handleDelete(row) {
      const ids = [row.id || this.ids]
      this.$confirm('确认删除已选中的数据项？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Api.removeMenus(ids).then(() => {
          this.$message.success('删除成功')
          this.handleQuery()
        })
      }).catch(() =>
        this.$message.info('已取消删除')
      )
    },
    // 重置
    resetForm() {
      this.form = {
        visible: 1,
        parentId: '0',
        icon: undefined,
        sort: 1,
        componentPath: ''
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    // 加载菜单项
    loadMenuOptions() {
      this.menuOptions = []
      Api.getMenuList({ queryMode: '1' }).then(data => {
        const menuOption = { id: '0', name: '顶级菜单', children: data.records }
        this.menuOptions.push(menuOption)
      })
    },
    // 图标选中
    handleIconSelected(name) {
      this.$set(this.form, 'icon', name)
    }
  }
}
</script>
